package com.xncoding.jwt.handler;


import com.fasterxml.jackson.core.type.TypeReference;
import com.xncoding.jwt.commons.JacksonUtil;
import com.xncoding.jwt.model.WsParam;
import com.xncoding.jwt.model.WsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * SocketHandler用于处理待办消息服务客户端会话相关业务
 *
 * @author feilong
 * @version 1.0
 * @since 2024/5/27
 */
@Component
public class SocketHandler extends TextWebSocketHandler {

    /***
     * 此参数用于服务器端响应客户端socket心跳内容
     */
    public static final String HEART_BEAT_SERVER_RESPONSE = "hb_ok";

    /***
     * 此参数用于客户端向服务器端发送的心跳内容
     */
    public static final String HEART_BEAT_CLIENT_RESPONSE = "hb";

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("handleTextMessage start");
        String msg = message.getPayload();
        log.info("msg = " + msg);
        //心跳检测
        if (msg != null && HEART_BEAT_CLIENT_RESPONSE.equals(msg)) {
            sendMessageToUser(session, new TextMessage(HEART_BEAT_SERVER_RESPONSE));
        } else {
            WsParam<String> wsParam = JacksonUtil.json2Bean(msg, new TypeReference<WsParam<String>>() {
            });
            if (wsParam != null && "list".equals(wsParam.getMethod())) {
                log.info("call list method...");
                WsResponse<String> response = new WsResponse<>();
                response.setResult("hello list");
                sendMessageToUser(session, new TextMessage(JacksonUtil.bean2Json(response)));
            }
        }
        log.info("handleTextMessage end");
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("Connected ... " + session.getId());
        SocketUsersHandler.addUser(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info(String.format("Session %s closed because of %s", session.getId(), status.getReason()));
        SocketUsersHandler.removeUser(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        log.error("error occurred at sender " + session, throwable);
    }


    /**
     * 发送消息给指定的用户
     *
     * @author feilong
     * @version 1.0
     * @since 2024/5/29
     */
    private void sendMessageToUser(WebSocketSession user, TextMessage message) {
        try {
            if (user.isOpen()) {
                user.sendMessage(message);
            }
        } catch (IOException e) {
            log.error("发送消息给指定的用户出错", e);
        }
    }
}
